package com.springfreemwork.tomcat;

import com.springfreemwork.properties.ServerProperties;
import com.springfreemwork.tomcat.servlet.DemoServlet;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.apache.catalina.Context;
import org.apache.catalina.Host;
import org.apache.catalina.Wrapper;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;
import org.apache.commons.lang3.ObjectUtils;

import javax.servlet.Servlet;
import java.util.HashMap;
import java.util.UUID;

/**
 * @author gpo12345678@163.com
 * @create 2024-04-03 10:11
 */


@Data
@AllArgsConstructor
public final class EmbeddedTomcatServer{


	private ServerProperties serverProperties;

	private HashMap<String, Servlet> servletMapping;


	public void run() {
		try {
			String classpath = System.getProperty("user.dir");
			Tomcat tomcat = new Tomcat();
			Connector connector = tomcat.getConnector();
			connector.setPort(serverProperties.getPort());
			Host host = tomcat.getHost();
			host.setName(serverProperties.getHost());
			host.setAppBase("webapps");
			Context context = tomcat.addContext(host,"/",classpath);

			if (context instanceof StandardContext) {
				//我们要把Servlet设置进去

				if(ObjectUtils.isEmpty(servletMapping)){
					Wrapper wrapper = tomcat.addServlet("/", "DemoServlet", new DemoServlet());
					wrapper.addMapping("/embeddedTomcat");
				}else {
					for (String name : servletMapping.keySet()) {
						Wrapper wrapper = tomcat.addServlet("/", UUID.randomUUID().toString(), servletMapping.get(name));
						wrapper.addMapping(name);
					}
				}
			}
			tomcat.start();
			tomcat.getServer().await();

		}catch (Exception e){
			e.printStackTrace();
		}
	}
}
